package com.mobileClientKernel.android.commonLayer;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;


import com.mobileClientKernel.android.commonLayer.DESUtil;
import com.mobileClientKernel.android.commonLayer.MD5Util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonUtils {


    private static long lastClickTime;
    private static SimpleDateFormat LOGFORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);

    /**
     * 将dp值转为px值
     *
     * @param context
     * @param dp
     * @return 手机当前px值
     */
    public static int dp2px(Context context, float dp) {
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        float density = displayMetrics.density;
        return (int) (density * dp + 0.5f);
    }


    // px2dp
    public static int px2dp(Context context, int px) {
        // px=dp*逻辑密度
        float density = context.getResources().getDisplayMetrics().density;
        return (int) (px / density + 0.5f);
    }

    /**
     * xml转View对象
     */
    public static View inflate(Context context, int layoutId) {
        return View.inflate(context, layoutId, null);
    }

    /**
     * 使用LayoutInflater 实例化View
     *
     * @param context
     * @return
     */
    public static View inflater(Context context, int layoutId, ViewGroup parent, boolean attachToRoot) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService
                (Context.LAYOUT_INFLATER_SERVICE);
        return inflater.inflate(layoutId, parent, attachToRoot);
    }

    /**
     * 获取本地String
     *
     * @return
     */
    public static String getString(int id,Application mainApplication) {
        return mainApplication.getResources().getString(id);
    }

    // 获取Drawable
    public static Drawable getDrawable(int id,Application mainApplication) {
        return mainApplication.getResources().getDrawable(id);
    }

    public static String[] getArray(int resID,Application mainApplication) {
        return mainApplication.getResources().getStringArray(resID);
    }

    public static int getColor(int colorID,Application mainApplication) {
        return mainApplication.getResources().getColor(colorID);
    }

    /**
     * 切换明密文
     *
     * @param editText
     */
    public static void switchPwdShow(EditText editText) {
        if (editText.getTransformationMethod() == PasswordTransformationMethod.getInstance()) {
            editText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            editText.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
        //设置光标位置到末尾
        moveInputCursor(editText);
    }


    //设置光标位置到末尾
    public static void moveInputCursor(EditText editText) {
        CharSequence text = editText.getText();
        if (text instanceof Spannable) {
            Spannable spanText = (Spannable) text;
            Selection.setSelection(spanText, text.length());
        }
    }





    /**
     * 获取当前系统时间，
     *
     * @return 格式2016-06-29 11:58:31
     */
    public static String getDateStr() {
        return LOGFORMAT.format(new Date(System.currentTimeMillis()));
    }

    /**
     * 获取当前系统时间，
     *
     * @return 格式20160629115831
     */
    public static String getDateStr2() {
        SimpleDateFormat format1 = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA);
        return format1.format(new Date(System.currentTimeMillis()));
    }

    /**
     * 获取当前系统时间，
     *
     * @return 格式2016/06/29 11:58:31
     */
    public static String getDateStr3() {
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.CHINA);
        return format1.format(new Date(System.currentTimeMillis()));
    }

    /**
     * 获取当前系统时间，
     *
     * @return 格式20160629115831
     */
    public static Date getDate(String date) {

        Date date1 = null;
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
        try {
            date1 = format1.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date1;
    }


    /**
     * 获取时间 20160801113214
     *
     * @param date
     * @return
     */
    public static Date getDate2(String date) {
        Date date1 = null;
        SimpleDateFormat format1 = new SimpleDateFormat("yyyyMMddHHmmss");
        try {
            date1 = format1.parse(date);
            date1.setHours(0);
            date1.setMinutes(0);
            date1.setSeconds(0);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date1;
    }


    /**
     * 获取时间 20160801113214
     *
     * @param date
     * @return
     */
    public static Date getDate3(String date) {
        Date date1 = null;
        SimpleDateFormat format1 = new SimpleDateFormat("yyyyMMddHHmmss");
        try {
            date1 = format1.parse(date);

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date1;
    }

    //获取时间 20160801113214 to 01.08.2016
    public static String getDateStr(String datastr) {
        Date date = getDate2(datastr);
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy/MM/dd");
        return format1.format(date);
    }


    //获取时间 2016-08-01 to 01.08.2016
    public static String getDateStr2(String datastr) {
        Date date = getDate(datastr);
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy/MM/dd");
        return format1.format(date);
    }

    //获取时间 date to 01.08.2016
    public static String getDateStrFromDate(Date date) {
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy/MM/dd");
        return format1.format(date);
    }


    //获取时间 20160801113214 to 2016/08/01 11:32:14
    public static String getDateStr3(String datastr) {
        Date date = getDate3(datastr);
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        return format1.format(date);
    }

    //获取时间 2016-08-01 2016/08/01
    public static String getDateStr4(String datastr) {
        Date date = getDate(datastr);
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy/MM/dd");
        return format1.format(date);
    }

    /**
     * 获取当前系统时间，
     *
     * @return 格式20160629115831
     */
    public static int getDiffDay(Date date1, Date date2) {
        if (date1 == null || date2 == null) {
            return 0;
        }

        long time1 = date1.getTime();
        long time2 = date2.getTime();
        return (int) ((time1 - time2) / (24 * 60 * 60 * 1000));
    }


    /**
     * 获取当前系统时间，
     *
     * @return 格式2016-01-05
     */
    public static String formatDateStr(String date) {
        Date date1 = null;
        try {
            date1 = new SimpleDateFormat("yyyy-MM-dd").parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.CHINA);
        return format1.format(date1);
    }




    /**
     * 数字转人民币,不满10000则不转
     *
     * @return
     */
    public static String transMoneyStr(int money) {
        if (money / 10000 < 1) {
            return money + "";
        } else {
            return money / 10000 + "万";
        }
    }

    /**
     * 检查当前网络是否可用
     *
     * @param activity
     * @return
     */
    public static boolean isNetworkAvailable(Context activity) {
        Context context = activity.getApplicationContext();
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivityManager == null) {
            return false;
        } else {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();
            if (networkInfo != null && networkInfo.length > 0) {
                for (int i = 0; i < networkInfo.length; i++) {
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }


    /**


    /**
     * 对象转byte
     *
     * @param obj
     * @return
     */
    public static byte[] obj2Byte(Object obj) {
        byte[] result = null;
        ByteArrayOutputStream baOptStream = new ByteArrayOutputStream();
        try {
            ObjectOutputStream objOptStream = new ObjectOutputStream(baOptStream);
            objOptStream.writeObject(obj);
            result = baOptStream.toByteArray();

            objOptStream.close();
            baOptStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }


    /**
     * byte 转 object
     *
     * @param bytes
     * @return
     */
    public static Object byte2Obj(byte[] bytes) {
        Object result = null;
        ByteArrayInputStream paIptStream = new ByteArrayInputStream(bytes);
        try {
            ObjectInputStream objIptStream = new ObjectInputStream(paIptStream);
            result = objIptStream.readObject();
            paIptStream.close();
            objIptStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        return result;
    }







    public static void setListViewHeightBasedOnChildren3(ListView listView, int heightDp) {

        //获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        int listCount = listAdapter.getCount();
        View view = listAdapter.getView(0, null, listView);
        view.measure(0, 0);

        for (int i = 0, len = listCount; i < len; i++) {   //listAdapter.getCount()返回数据项的数目
            totalHeight += dp2px(listView.getContext(), heightDp);
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listCount - 1));

        //listView.getDividerHeight()获取子项间分隔符占用的高度
        //params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);

    }

    /**
     * 设置popwindow背景色
     *
     * @param context
     * @param a
     */
    public static void setBackgroundColor(Activity context, float a) {
        WindowManager.LayoutParams lp = context.getWindow().getAttributes();
        lp.alpha = a;
        context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        context.getWindow().setAttributes(lp);
    }

    /**
     * 从asset中读取json
     *
     * @param mContext
     * @param fileName
     * @return
     */
    public static String getJson(Context mContext, String fileName) {
        // TODO Auto-generated method stub
        StringBuilder sb = new StringBuilder();
        AssetManager am = mContext.getAssets();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    am.open(fileName)));
            String next = "";
            while (null != (next = br.readLine())) {
                sb.append(next);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            sb.delete(0, sb.length());
        }
        return sb.toString().trim();
    }






    /**
     * 判断是否重复点击
     *
     * @return
     */
    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < 500) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    /**
     * 隐藏键盘
     *
     * @param context
     */
    public static void hideSoftInput(Activity context) {

        View focusView = context.getCurrentFocus();
        if (focusView == null) {
            return;
        }
        ((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(focusView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 显示键盘
     *
     * @param activity
     * @param editText
     */
    public static void showSoftInput(Activity activity, EditText editText) {
        ((InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(editText, 0);
    }


    public static boolean checkIdcard(String value) {
        int length = 0;
        if (value == null) {
            return false;
        } else {
            length = value.length();


            if (length != 15) {
            } else if (length != 18) {
            } else {
                return false;
            }
        }
        String[] areasArray = {"11", "12", "13", "14", "15", "21", "22", "23", "31",
                "32", "33", "34", "35", "36", "37", "41", "42", "43", "44",
                "45", "46", "50", "51", "52", "53", "54", "61", "62", "63",
                "64", "65", "71", "81", "82", "91"};


        HashSet<String> areasSet = new HashSet<String>(Arrays.asList(areasArray));
        String valueStart2 = value.substring(0, 2);


        if (areasSet.contains(valueStart2)) {
        } else {
            return false;
        }

        Pattern pattern = null;
        Matcher matcher = null;


        int year = 0;
        switch (length) {
            case 15:
                year = Integer.parseInt(value.substring(6, 8)) + 1900;


                if (year % 4 == 0 || (year % 100 == 0 && year % 4 == 0)) {
                    pattern = Pattern.compile("^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$"); // 测试出生日期的合法性
                } else {
                    pattern = Pattern.compile("^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$"); // 测试出生日期的合法性
                }
                matcher = pattern.matcher(value);
                return matcher.find();
            case 18:
                year = Integer.parseInt(value.substring(6, 10));

                /*出生日期之前版本只有1900～1999，720版本添加了2000～2010*/
                if (year % 4 == 0 || (year % 100 == 0 && year % 4 == 0)) {
                    pattern = Pattern.compile("^[1-9][0-9]{5}(19[0-9]{2}|200[0-9]|2010)((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$"); // 测试出生日期的合法性
                } else {
                    pattern = Pattern.compile("^[1-9][0-9]{5}(19[0-9]{2}|200[0-9]|2010)((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$"); // 测试出生日期的合法性
                }


                matcher = pattern.matcher(value);
                if (matcher.find()) {
                    int S = (Integer.parseInt(value.substring(0, 1)) + Integer.parseInt(value.substring(10, 11))) * 7 + (Integer.parseInt(value.substring(1, 2)) + Integer.parseInt(value.substring(11, 12))) * 9 + (Integer.parseInt(value.substring(2, 3)) + Integer.parseInt(value.substring(12, 13))) * 10 + (Integer.parseInt(value.substring(3, 4)) + Integer.parseInt(value.substring(13, 14))) * 5 + (Integer.parseInt(value.substring(4, 5)) + Integer.parseInt(value.substring(14, 15))) * 8 + (Integer.parseInt(value.substring(5, 6)) + Integer.parseInt(value.substring(15, 16))) * 4 + (Integer.parseInt(value.substring(6, 7)) + Integer.parseInt(value.substring(16, 17))) * 2 + Integer.parseInt(value.substring(7, 8)) * 1 + Integer.parseInt(value.substring(8, 9)) * 6 + Integer.parseInt(value.substring(9, 10)) * 3;
                    int Y = S % 11;
                    String M = "F";
                    String Ml = "F";
                    String JYM = "10X98765432";
                    String JYMl = "10x98765432";
                    M = JYM.substring(Y, Y + 1); // 判断校验位
                    Ml = JYMl.substring(Y, Y + 1);
                    if (M.equals(value.substring(17, 18))) {
                        return true; // 检测ID的校验位
                    } else {
                        return Ml.equals(value.substring(17, 18));

                    }
                } else {
                    return false;
                }
            default:
                return false;
        }
    }



    public static String getCryptText(EditText editText) {
        String dev = UniqueIDUtil.getDeviceId(editText.getContext());
        JJLog._d("JJ", "DEditText device id " + dev);
        String key = "";
        if (dev.length() == 8) {
            key = dev;
        } else {
            key = dev.substring(0, 8);
        }
        String despwd = "";
        String pwd = editText.getText().toString().trim();
        try {
            despwd = DESUtil.encryptDES(pwd, key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return despwd;

    }


    /**
     * 去除list中的重复元素
     *
     * @param list
     * @return
     */
    public static List removeDup(List list) {
        Set set = new HashSet<>();
        List listTemp = new ArrayList<>();
        for (Object obj : list) {
            if (set.add(obj)) {
                listTemp.add(obj);
            }
        }

        return listTemp;
    }

    public static String formatTosepara(String data) {
        if (TextUtils.isEmpty(data)) {
            return "0.00";
        }
        if ("0".equals(data)) {
            return "0.00";
        }

        if (Double.parseDouble(data) < 1) {
            return data;
        }
        BigDecimal b = new BigDecimal(data);

        DecimalFormat df = new DecimalFormat("#,###.00");

        return df.format(b.setScale(2, BigDecimal.ROUND_HALF_UP));
    }

    public static String getDeskey(Context context) {
        String md5 = MD5Util.getMD5Code(context.getPackageName()).substring(0, 8);
        return md5;
    }

    public static void main(String arg[]) {
      /*  Random random=new Random();
        for (int i=0;i<100;i++){
            float v = random.nextFloat();
            System.out.println(v*100000+v+"随机生成"+formatTosepara(v*100000+v+""));
        }*/

    }







    private static String[] known_files = {
            "/system/lib/libc_malloc_debug_qemu.so",
            "/sys/qemu_trace",
            "/system/bin/qemu-props"};

    /**
     * 判断是否模拟器
     *
     * @return
     */
    public static Boolean CheckEmulatorFiles() {
        for (int i = 0; i < known_files.length; i++) {
            String file_name = known_files[i];
            File qemu_file = new File(file_name);
            if (qemu_file.exists()) {
                return true;
            }
        }
        return false;
    }


    /**
     * 检查设备是否被root
     * @return
     */
    public static boolean checkRootWhichSU() {
        String[] strCmd = new String[]{"/system/xbin/which", "su"};
        ArrayList<String> execResult = executeCommand(strCmd);
        if (execResult != null) {
            return true;
        } else {
            return false;
        }
    }

    public static ArrayList<String> executeCommand(String[] shellCmd) {
        String line = null;
        ArrayList<String> fullResponse = new ArrayList<String>();
        Process localProcess = null;
        try {
            localProcess = Runtime.getRuntime().exec(shellCmd);
        } catch (Exception e) {
            return null;
        }
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(localProcess.getOutputStream()));
        BufferedReader in = new BufferedReader(new InputStreamReader(localProcess.getInputStream()));
        try {
            while ((line = in.readLine()) != null) {
                fullResponse.add(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fullResponse;
    }

    /**
     * 比较版本号的大小,前者大则返回一个正数,后者大返回一个负数,相等则返回0
     * @param version1
     * @param version2
     * @return
     */
    public static int compareVersion(String version1, String version2) throws Exception {
        if (version1 == null || version2 == null) {
            throw new Exception("compareVersion error:illegal params.");
        }
        String[] versionArray1 = version1.split("\\.");//注意此处为正则匹配，不能用"."；
        String[] versionArray2 = version2.split("\\.");
        int idx = 0;
        int minLength = Math.min(versionArray1.length, versionArray2.length);//取最小长度值
        int diff = 0;
        while (idx < minLength
                && (diff = versionArray1[idx].length() - versionArray2[idx].length()) == 0//先比较长度
                && (diff = versionArray1[idx].compareTo(versionArray2[idx])) == 0) {//再比较字符
            ++idx;
        }
        //如果已经分出大小，则直接返回，如果未分出大小，则再比较位数，有子版本的为大；
        diff = (diff != 0) ? diff : versionArray1.length - versionArray2.length;
        return diff;
    }


}
